<template>
  <div>
    <Category :scene="scene"></Category>
    <el-card shadow="hover" style="margin: 10px 0;">
      <div v-if="scene === 0">
        <div v-if="attr.length">
          <el-button @click="addAttr" :icon="Plus" type="primary" :disabled="categoryStore.c3Id ? false : true">添加属性
          </el-button>
          <el-table border style="margin: 10px 0px;" :data="attr">
            <el-table-column type="index" align="center" width="80" label="序号"></el-table-column>
            <el-table-column label="属性名称" prop="attrName"></el-table-column>
            <el-table-column prop="attrValueName.valueName" label="属性值名称">
              <!-- 作用域插槽 -->
              <template #="{ row, $index }">
                <el-tag style="margin:5px" v-for="attrValueName in row.attrValueList" :key="attrValueName.id"
                  type="primary">
                  {{ attrValueName.valueName }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="属性操作" width="240">
              <template #="{ row, $index }">
                <el-button type="warning" :icon="Edit" @click="updateAttr(row)"></el-button>
                <el-popconfirm :title="`你确定删除${row.attrName}?`" width="250" @confirm="handler(row.id)">
                  <template #reference>
                    <el-button type="danger" :icon="Delete"></el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-empty description="暂无数据" v-else />
      </div>
      <div v-else>
        <el-form>
          <el-form-item label="属性名称">
            <el-input placeholder="属性名称" style="width: 205px;" v-model="attrParams.attrName"></el-input>
          </el-form-item>
        </el-form>
        <el-button :icon="Plus" type="primary" @click="addAttrValue"
          :disabled="attrParams.attrName.trim() === ''">添加属性</el-button>
        <el-button @click="cancel">取消</el-button>
        <el-table border style="margin: 10px 0px;" :data="attrParams.attrValueList">
          <el-table-column align="center" width="80" label="序号" type="index"></el-table-column>
          <el-table-column label="属性值">
            <template #="{ row, $index }">
              <el-input ref="inputElement" v-if="row.showInput" @blur="toLook(row, $index)" placeholder="请输入属性值"
                v-model="row.valueName"></el-input>
              <div v-else @click="toEdit(row)">{{ row.valueName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="属性操作">
            <!-- 删除属性值 -->
            <template #="{ row, $index }">
              <el-popconfirm @confirm="attrParams.attrValueList.splice($index, 1)" :title="`你确定删除${row.valueName}?`"
                width="250">
                <template #reference>
                  <el-button :icon="Delete" type="danger"></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" @click="save" :disabled="attrParams.attrValueList.length ? false : true">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { Plus, Edit, Delete } from '@element-plus/icons-vue';
import { watch, ref, reactive, nextTick } from 'vue';
import useCategoryStore from '@/stores/category';
import type { AttrArr, Attr, AttrValueList } from '@/api/product/attr/interface';
import { reqAttrList, reqAddOrUpdateAttr, reqDeleteAttr } from '@/api/product/attr';
import { ElMessage } from 'element-plus';
//获取小仓库
const categoryStore = useCategoryStore();
//响应式数据控制场景切换
const scene = ref<number>(0);
const showInput = ref(true)
const attr = ref<any>([]);
//获取input组件实例
const inputElement = ref<any>();
//监听到三级分类变化去获取属性与属性值
watch(() => categoryStore.c3Id, () => {
  attr.value = ''
  // 前者为真执行，前提保证三级分类ID不能为空
  categoryStore.c3Id && getAttr();
})
//获取属性与属性值方法
const getAttr = async () => {
  const { c1Id, c2Id, c3Id } = categoryStore;
  const result: AttrArr = await reqAttrList(c1Id as number, c2Id as number, c3Id as number);
  attr.value = result
}
// 收集数据
const attrParams = reactive<Attr>({
  attrName: '',
  attrValueList: [
  ],
  categoryLevel: 3,
  categoryId: 0
})
// 添加属性
const addAttr = () => {
  scene.value = 1;
  attrParams.attrName = '';
  attrParams.attrValueList = [];
  attrParams.id = undefined;
  // 收集三级分类的ID
  attrParams.categoryId = categoryStore.c3Id as number;
}
// 更新属性
const updateAttr = (row: Attr) => {
  scene.value = 1;
  //深拷贝与浅拷贝  --JSON|lodash
  Object.assign(attrParams, JSON.parse(JSON.stringify(row)))
}
// 取消按钮
const cancel = () => {
  scene.value = 0;
}
// 添加属性值
const addAttrValue = () => {
  attrParams.attrValueList.push({
    valueName: '',
    id: 0,
    showInput: true
  });
  // 获取表单元素聚焦
  nextTick(() => {
    inputElement.value.focus();
  })
}
// 点击保存
const save = async () => {
  await reqAddOrUpdateAttr(attrParams);
  ElMessage({
    type: 'success',
    message: `${attrParams.id ? '更新' : '添加'}成功`
  });
  scene.value = 0;
  getAttr()
}
//查看模式---显示div
const toLook = (row: AttrValueList, index: any) => {
  // 如果属性值为空
  if (row.valueName.trim() === "") {
    ElMessage({
      type: 'error',
      message: '属性值不能为空'
    });
    // 清空属性值输入框
    attrParams.attrValueList.splice(index, 1);
    return;
  }
  const reqeat = attrParams.attrValueList.find((addAttrValue) => {
    if (row != addAttrValue) {
      return addAttrValue.valueName == row.valueName
    }
  })
  if (reqeat) {
    ElMessage({
      type: 'error',
      message: '属性值不能重复'
    });
    // 不符合条件，删除数组中最后一个（正在编辑的输入框）
    attrParams.attrValueList.splice(index, 1);
    return;
  }
  row.showInput = false;
}
//编辑模式---显示input
const toEdit = (row: AttrValueList) => {
  row.showInput = true;
  // 获取表单元素聚焦
  nextTick(() => {
    inputElement.value.focus();
  })
}
// 删除
const handler = async (id: number) => {
  // 删除已有属性
  await reqDeleteAttr(id);
  ElMessage({
    type: 'success',
    message: '删除成功'
  });
  // 更新数据
  getAttr();
}
</script>

<script lang="ts">
name: 'trademark'
</script>

<style scoped></style>